<?php

namespace App\Service\Third;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Green\Green;
use App\Constants\ErrorCode;
use App\Exception\ApiException;
use App\Helpers\AliyunUtil;
use App\Model\Message;
use App\Model\VideoCall;
use App\Model\VideoCallAuditLog;
use App\Service\BaseService;
use Qiniu\Auth;
use Qiniu\Http\Client;
use App\Helpers\ImUtil;
use App\Model\UserDevice;
use App\Model\UserProfile;
use App\Model\UserFreezeLog;
use App\Model\User;
class VideoCheckService extends BaseService
{
    public function handle()
    {
        $picUrl = $this->request->input('pic_url');
        $videoId = $this->request->input('video_id');

        $videoCall = VideoCall::where(['channel_id' => $videoId])->first();
        if (empty($videoCall)) {
            throw new ApiException('视频通话不存在');
        }
      
        $resCheck = $this->qnCheck($picUrl);
//	      return $this->setError(ErrorCode::USER_NOT_VALID, $resCheck);       
	if ('pass' == $resCheck) {
            return ['msg' => 'success'];
        }

        // 挂断消息
        Message::sendSlient($videoCall['user_id'], 'VIDEO_YELLOW_TIP', [
            'time' => 5,
            'tip'  => '系统鉴别视频中存在违规内容，通话',
            'endtip' => 's后将被挂断！',
        ]);
        // 挂断消息
        Message::sendSlient($videoCall['chat_user_id'], 'VIDEO_YELLOW_TIP', [
            'time' => 5,
            'tip'  => '系统鉴别视频中存在违规内容，通话',
            'endtip' => 's后将被挂断！',
        ]);

        // 添加违规审核记录
        (new VideoCallAuditLog())->addAuditLog($videoId, $videoId, '', '', json_encode($resCheck, JSON_UNESCAPED_UNICODE));

        //封号
        $user_id = $videoCall['user_id'];
        $userInfo = UserProfile::getProfile($user_id);
        if ($userInfo->gender == 0) {
            User::freezeAccount($user_id);
            ImUtil::kickOut($user_id);
            UserDevice::freezeUserDevice($user_id);
            //理由
            UserFreezeLog::addRecord($user_id, 3, 1, '检测到涉黄');//3检测到涉黄
        }
        //封号
        $chat_user_id = $videoCall['chat_user_id'];
        $chatUserInfo = UserProfile::getProfile($chat_user_id);
        if ($chatUserInfo->gender == 0) {
            User::freezeAccount($chat_user_id);
            ImUtil::kickOut($chat_user_id);
            UserDevice::freezeUserDevice($chat_user_id);
            //理由
            UserFreezeLog::addRecord($chat_user_id, 3, 1, '检测到涉黄');//3检测到涉黄
        }

        return ['msg' => 'success'];
    }

    private function qnCheck($picUrl)
    {
        $accessKey = env('QN_ACCESS_KEY','');
        $secretKey = env('QN_SECRET_KEY','');

        if (empty($accessKey) || empty($secretKey)) {
            throw new ApiException('七牛鉴黄参数错误', ErrorCode::DEFAULT_ERROR);
        }

        $host = 'ai.qiniuapi.com';
        $uri = 'http://ai.qiniuapi.com/v3/image/censor';

        $contentType = 'application/json';
        $method = 'POST';
        $scenes = ['pulp'];

        $body = [
            'data' => ['uri' => $picUrl],
            'params' => ['scenes' => $scenes]
        ];

        $auth = new Auth($accessKey,$secretKey);
        $headers = $auth->authorizationV2($uri, $method,json_encode($body), $contentType);
        $headers['Content-Type'] = $contentType;
        $headers['Host'] = $host;

        $httpReq = Client::post($uri, json_encode($body),$headers);

        $res = json_decode($httpReq->body,true);
        log_info('QN_CHECK:检测回报参数:'.json_encode($res, JSON_UNESCAPED_UNICODE));

	//return $res;
        if (!isset($res['code']) || $res['code'] != 200) {
            log_info(  "QN_CHECK:==callbackArray:" . json_encode($res, JSON_UNESCAPED_UNICODE));

            throw new ApiException('回调数据错误', ErrorCode::DEFAULT_ERROR);
        }

        if ($res['result']['scenes']['pulp']['suggestion'] == 'pass') {
            return 'pass';
        }

        return $res;
    }

    private function aliyunCheck($picUrl)
    {
        $client = AliyunUtil::getClient();
        AlibabaCloud::accessKeyClient(config('aliyun.accessKeyId'), config('aliyun.accessKeySecret'))->regionId('cn-shenzhen')->asDefaultClient();

        $task1 = array(
            'dataId' => '1',
            'url' => $picUrl
        );

        $response = Green::v20180509()->imageSyncScan()->body(json_encode([
            'tasks' => [$task1],
            'scenes' => ['porn', 'terrorism', 'ad'],
            'bizType' => 'private_chat'
        ]))->request();
        $result = $response->toArray();

        log_info(__CLASS__.':鉴黄数据:'.json_encode($result));

        if (200 != $response->code) {
            log_info(__CLASS__ . "==callbackArray:" . json_encode($result, JSON_UNESCAPED_UNICODE));

            throw new ApiException('回调数据错误', ErrorCode::DEFAULT_ERROR);
        }

        //做判断逻辑处理
    }
}
